package com.heima.kafka;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * kafka 生产者
 */
public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1.kafka的配置信息
        Properties properties = getProperties();

        // 2.生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        // 封装发送的消息
        ProducerRecord<String, String> record = new ProducerRecord<>("topic--", "100001", "hello kafka");

        // 3.发送消息
        producer.send(record);

        // 同步阻塞  获取消息的元数据 -- 获取消息的偏移量
        RecordMetadata recordMetadata = producer.send(record).get();
        System.out.println("消息元数据 {偏移量} 为: " + recordMetadata.offset());

        // 异步非阻塞 发送消息时指定回调函数
        producer.send(record, (rmData, e) -> {
                if (e != null) {
                    e.printStackTrace();
                }
                System.out.println("消息偏移量：" + rmData.offset());
            }
        );

        // 4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }

    private static Properties getProperties() {
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 5);
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");
        return properties;
    }
}
